package jmine.tec.rpc.server.representation.representers.reflection;

import java.beans.PropertyDescriptor;
import java.util.List;

import jmine.tec.rpc.server.representation.RepresentationContext;

import org.apache.commons.beanutils.PropertyUtils;

/**
 * Representador de propriedades que são listas.
 * 
 * @author lundberg
 * @param <R> tipo de representação
 * @param <E> tipo de entidade representada
 */
public class ListPropertyRepresenter<R, E> implements PropertyRepresenter<R, E> {

    /**
     * {@inheritDoc}
     */
    public boolean isApplicableTo(PropertyDescriptor representationProperty) {
        return RepresenterUtil.classesMatch(List.class, representationProperty);
    }

    /**
     * {@inheritDoc}
     */
    public void representProperty(RepresentationContext context, R representation, PropertyDescriptor representationProperty, E object)
            throws Exception {
        Class<?> valueType = RepresenterUtil.getParameterizedPropertyType(representationProperty, 0, representation.getClass());
        List<?> value = (List<?>) PropertyUtils.getProperty(object, representationProperty.getName());
        List<?> valueRepresentation = this.createRepresentation(context, valueType, value);
        PropertyUtils.setProperty(representation, representationProperty.getName(), valueRepresentation);
    }

    /**
     * Cria uma representação da lista
     * 
     * @param context context
     * @param valueType valueType
     * @param value value
     * @return List
     */
    protected List<?> createRepresentation(RepresentationContext context, Class<?> valueType, List<?> value) {
        return context.representObjects(valueType, value);
    }
}
